<template>
    <el-form :inline="true" :model="ruleForm" class="demo-form-inline">
      <el-form-item label="供应商：">
        <el-select v-model="ruleForm.supId" clearable style="width: 310px; margin-left: 10px;" placeholder="请选择供应商">
          <el-option v-for="customer in show" :key="customer.id" :label="customer.supName" :value="customer.supId" />
        </el-select>
  
  
      </el-form-item>
  
      <el-form-item label="单据编号">
        <el-input v-model="ruleForm.number" placeholder="自动生成单据编号" readonly></el-input>
      </el-form-item>
  
      <el-form-item label="创建时间">
        <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
  
      <el-form-item label="财务人员：">
        <el-select v-model="ruleForm.handsPersonId" clearable style="width: 200px; margin-left: 10px;"
          placeholder="请选择财务人员">
          <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName" :value="persons.perId" />
          <el-option :value="undefined" disabled style="cursor: pointer">
            <el-button type="text" v-perm:finance:revenue:insert:financestaff="insert">
              <i class="el-icon-menu"></i>新增财务人员
            </el-button>
          </el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" class="ant-btn ant-btn-primary" style="margin-right: 10px;" plain
        v-perm:finance:payment:collectionpayfind="insert">
        <el-icon class="el-icon-left">
          <Plus />
        </el-icon>
        <span>选择单据</span>
      </el-button>
      <el-table :data="tableData" show-summary style="width: 100%">
        <el-table-column v-if="showIdColumn" label="id" width="400">
          <template #default="{ row }">
            <el-input v-model="row.id"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="采购单据编号" width="400">
          <template #default="{ row }">
            <el-input v-model="row.xm" placeholder="请输入销售单据编号"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="应付欠款" width="400">
          <template #default="{ row }">
            <el-input v-model="row.je" placeholder="请输入营收欠款"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="已付欠款" width="400">
          <template #default="{ row }">
            <el-input v-model="row.qk" placeholder="请输入已收欠款"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="本次付款" width="400">
          <template #default="{ row }">
            <el-input v-model="row.sk" placeholder="请输入已收欠款"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="400">
          <template #default="{ row }">
            <el-input v-model="row.bz" placeholder="请输入备注"></el-input>
          </template>
        </el-table-column>
      </el-table>
  
  
      <div class="index-body zb">
        <el-form-item label="付款账户：" style="margin-right: 120px;">
          <el-select clearable style="width: 200px;" placeholder="请选择账户" v-model="ruleForm.accountId">
            <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />
          </el-select>
        </el-form-item>
  
        <el-form-item label="合计付款：" style="margin-right: 100px;">
          <el-input style="width: 240px" :value="totalReceived" readonly></el-input>
        </el-form-item>
  
  
        <el-form-item label="优惠金额：" style="margin-right: 100px;">
          <el-input style="width: 240px" v-model="discountAmount"></el-input>
        </el-form-item>
        <el-form-item label="实际付款：" style="margin-right: 100px;">
          <el-input style="width: 240px" :value="actualReceived" readonly></el-input>
        </el-form-item>
  
      </div>
  
      <div class="ant-coloery" style="margin-right: 10px;">
        <el-form-item label="附件：">
          <el-button plain>
            <el-icon style="margin-right: 10px;">
              <MessageBox />
            </el-icon>上传附件
          </el-button>
        </el-form-item>
      </div>
    </el-form>
  
    <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="80%"
      style="margin-left: 250px; margin-top: 200px">
      <router-view @close="close" :data="data" :supId="ruleForm.supId" @table="proty"></router-view>
    </el-dialog>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue';
  import router from '@/router';
  import request from '@/api/request';
  import { ElMessage } from 'element-plus';
  import { computed } from 'vue';
  
  // 计算实际收款总和
  const totalReceived = computed(() => {
    return tableData.value.reduce((sum, row) => sum + (parseFloat(row.sk) || 0), 0);
  });
  // 定义优惠金额的响应式变量
  const discountAmount = ref(0); // 用于存储优惠金额
  
  const actualReceived = computed(() => {
    const total = totalReceived.value; // 使用合计收款计算
    return total - discountAmount.value; // 减去优惠金额
  });
  
  
  const visible = ref(false);
  const title = ref("");
  const data = ref({});
  const ruleForm = ref({
    supId: '',
    linkNumber: '',
    number: '',
    organId: '',
    accountId: '',
    handsPersonId: '',
    discountAmount: '',
    actualReceived: ''
  });
  
  const close = () => {
    visible.value = false;
  };
  
  const tableData = ref([{ barCode: '', categoryName: '', color: '' }]);
  
  const addRow = () => {
    tableData.value.push({
      barCode: '',
      categoryName: '',
      color: '',
    });
  };
  const show = ref([]);
  const loadCushowstomers = () => {
    request({
      url: '/basic/vendor/list2',
      method: 'get',
      params:{
        subType:'0'
      }
    }).then(res => {
  
      show.value = res.data; // 更新客户数据
    }).catch(err => {
      console.error(err);
    });
  };
  loadCushowstomers();
  const accounts = ref([]);
  const loadAccounts = () => {
    request({ url: '/basic/account/list', method: 'get' })
      .then(res => accounts.value = res.data)
      .catch(err => console.error(err));
  };
  loadAccounts();
  const submitForm = () => {
    const totalAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.je) || 0), 0);
    const changeAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.sk) || 0), 0);
  
    const data = {
  erpAccountHead: {
    type: '付款',
    billNo: ruleForm.value.number,
    organId: ruleForm.value.supId,
    creator: '1',
    accountId: ruleForm.value.accountId,
    handsPersonId: ruleForm.value.handsPersonId,
    changeAmount: -changeAmount, // 将 changeAmount 变为负数
    totalPrice: -totalAmount,     // 将 totalAmount 变为负数
    discountMoney: discountAmount.value,
    actualReceived: actualReceived.value,
    status: '0',
  },
  erpAccountItems: tableData.value.map(row => ({
    remark: row.bz || '',
    billId: row.id, // 修改这里来引用每个行的 billId
    eachAmount: -row.sk,
    needDebt: row.je,
    finishDebt: row.qk,
  })),
}

    request({
      url: '/accountHead/insertFind',
      method: 'post',
      data: data,
      headers: { 'Content-Type': 'application/json' },
    }).then(res => {
      console.log(res);
      ElMessage.success('提交成功');
    }).catch(err => {
      console.error(err);
      ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
    });
  };
  
  const handleSave = (selectedItems) => {
    console.log('选中的数据:', selectedItems);
    // 进一步处理选中的数据
  };
  
  // Other functions...  
  const stausData = [
    { id: '1', name: '利息收入' },
    { id: '2', name: '房租收入' }
  ];
  
  let save = ref([]);
  const proty = (items) => {
    console.log("proty被调用", items);
  
    // 清空现有的行
    tableData.value = [];
  
    // 遍历传入的多条数据
    items.forEach((item) => {
      tableData.value.push({
        id: item.id,  // 确保每个行都有 id 属性
        xm: item.number,
        je: item.erpAccountItem.adjustedDiscount,
        qk: Math.abs(item.erpAccountItem.eachAmount || 0),
        bz: item.remark || '',
        billId: item.id // 这里可以保留，也可以换成其他合适的字段
      });
    });
  };
  
  
  
  
  
  const customers = ref([]); // 存储客户数据  
  
  const loadCustomers = () => {
    request({ url: '/basic/vendor/findBy', method: 'get' })
      .then(res => {
        console.log(res);
        customers.value = res.data; // 更新客户数据  
      }).catch(err => {
        console.error(err);
      });
  };
  loadCustomers();
  
  const person = ref({});
  const personfin = () => {
    request({ url: '/basic/person/list', method: 'get' })
      .then(res => {
        person.value = res.data;
        console.log(res);
      });
  }
  personfin();
  
  const insert = (p) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    personfin();
  };
  
  // 页面加载时生成订单编号  
  onMounted(() => {
    let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);
    currentOrderNumber++;
    const formattedOrderNumber = currentOrderNumber.toString().padStart(10, '0');
    ruleForm.value.number = formattedOrderNumber;
    localStorage.setItem('orderNumber', currentOrderNumber.toString());
  });
  </script>
  
  <style>
  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }
  
  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
  </style>